// 页面内的调试器界面
let debugPanel = null;
let isDebugPanelVisible = false;
let debugData = [];

// 初始化调试面板
function initDebugPanel() {
    if (debugPanel) {
        return;
    }

    // 创建调试面板
    debugPanel = document.createElement('div');
    debugPanel.id = 'ws-debugger-panel';
    debugPanel.style.cssText = `
    position: fixed;
    bottom: 0;
    right: 0;
    width: 400px;
    height: 400px;
    background-color: rgba(0, 0, 0, 0.8);
    color: #fff;
    font-family: monospace;
    z-index: 9999;
    display: flex;
    flex-direction: column;
    border-top-left-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    font-size: 12px;
    overflow: hidden;
  `;

    // 创建标题栏
    const titleBar = document.createElement('div');
    titleBar.style.cssText = `
    padding: 8px;
    background-color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;
  `;

    const title = document.createElement('div');
    title.textContent = 'WebSocket 调试器';
    title.style.fontWeight = 'bold';

    const closeButton = document.createElement('button');
    closeButton.textContent = '×';
    closeButton.style.cssText = `
    background: none;
    border: none;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
  `;
    closeButton.onclick = toggleDebugPanel;

    titleBar.appendChild(title);
    titleBar.appendChild(closeButton);

    // 创建内容区域
    const content = document.createElement('div');
    content.style.cssText = `
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  `;
    content.id = 'ws-debugger-content';

    // 创建命令输入区域
    const commandArea = document.createElement('div');
    commandArea.style.cssText = `
    padding: 8px;
    background-color: #222;
    display: flex;
    flex-direction: column;
    gap: 8px;
  `;

    // 添加提示标签
    const commandLabel = document.createElement('div');
    commandLabel.textContent = '执行浏览器命令：';
    commandLabel.style.cssText = `
    font-size: 12px;
    color: #aaa;
  `;
    commandArea.appendChild(commandLabel);

    // 创建输入框和按钮的容器
    const inputContainer = document.createElement('div');
    inputContainer.style.cssText = `
    display: flex;
    gap: 8px;
  `;

    // 创建命令输入框
    const commandInput = document.createElement('input');
    commandInput.id = 'ws-debugger-command-input';
    commandInput.placeholder = '输入 JS 命令...';
    commandInput.style.cssText = `
    flex: 1;
    padding: 6px 8px;
    border: 1px solid #444;
    border-radius: 4px;
    background-color: #111;
    color: #fff;
    font-family: monospace;
    font-size: 12px;
  `;

    // 创建执行按钮
    const executeButton = document.createElement('button');
    executeButton.textContent = '执行';
    executeButton.style.cssText = `
    padding: 6px 12px;
    background-color: #4285f4;
    border: none;
    border-radius: 4px;
    color: white;
    cursor: pointer;
    font-size: 12px;
  `;
    executeButton.onclick = executeCommand;

    // 创建清除按钮
    const clearButton = document.createElement('button');
    clearButton.textContent = '清除';
    clearButton.style.cssText = `
    padding: 6px 12px;
    background-color: #db4437;
    border: none;
    border-radius: 4px;
    color: white;
    cursor: pointer;
    font-size: 12px;
  `;
    clearButton.onclick = clearCommandResult;

    // 添加到容器
    inputContainer.appendChild(commandInput);
    inputContainer.appendChild(executeButton);
    inputContainer.appendChild(clearButton);
    commandArea.appendChild(inputContainer);

    // 创建命令结果显示区域
    const resultArea = document.createElement('div');
    resultArea.id = 'ws-debugger-result';
    resultArea.style.cssText = `
    margin-top: 8px;
    padding: 8px;
    background-color: #111;
    border: 1px solid #444;
    border-radius: 4px;
    min-height: 60px;
    max-height: 120px;
    overflow-y: auto;
    font-family: monospace;
    font-size: 12px;
    white-space: pre-wrap;
    word-break: break-all;
  `;
    commandArea.appendChild(resultArea);

    // 创建状态栏
    const statusBar = document.createElement('div');
    statusBar.style.cssText = `
    padding: 8px;
    background-color: #333;
    display: flex;
    justify-content: space-between;
    font-size: 11px;
  `;
    statusBar.id = 'ws-debugger-status';
    statusBar.textContent = '状态：未连接';

    // 组装面板
    debugPanel.appendChild(titleBar);
    debugPanel.appendChild(content);
    debugPanel.appendChild(commandArea);
    debugPanel.appendChild(statusBar);

    // 让面板可拖动
    let isDragging = false;
    let dragOffsetX, dragOffsetY;

    titleBar.addEventListener('mousedown', (e) => {
        isDragging = true;
        dragOffsetX = e.clientX - debugPanel.getBoundingClientRect().left;
        dragOffsetY = e.clientY - debugPanel.getBoundingClientRect().top;
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;

        const x = e.clientX - dragOffsetX;
        const y = e.clientY - dragOffsetY;

        debugPanel.style.left = `${x}px`;
        debugPanel.style.right = 'auto';
        debugPanel.style.top = `${y}px`;
        debugPanel.style.bottom = 'auto';
    });

    document.addEventListener('mouseup', () => {
        isDragging = false;
    });

    // 添加按 Enter 键执行命令的功能
    commandInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            executeCommand();
        }
    });

    // 将面板添加到页面
    document.body.appendChild(debugPanel);

    // 初始隐藏
    debugPanel.style.display = 'none';
}

// 执行浏览器命令
function executeCommand() {
    const commandInput = document.getElementById('ws-debugger-command-input');
    const resultArea = document.getElementById('ws-debugger-result');

    if (!commandInput || !resultArea) return;

    const command = commandInput.value.trim();
    if (!command) return;

    // 检查是否是特殊浏览器命令
    if (command === 'clearCookies' ||
        command === 'reload' ||
        command.startsWith('navigate:')) {

        // 发送命令到 background.js 处理
        chrome.runtime.sendMessage({ type: 'execute_browser_command', command: command },
            (response) => {
                // 显示执行结果
                const resultElement = document.createElement('div');
                resultElement.style.cssText = `
                    margin-bottom: 8px;
                    padding-bottom: 8px;
                    border-bottom: 1px solid #444;
                `;

                // 添加命令
                const commandElement = document.createElement('div');
                commandElement.style.color = '#4285f4';
                commandElement.textContent = '> ' + command;

                // 添加结果
                const outputElement = document.createElement('div');

                if (response && response.success) {
                    outputElement.style.color = '#0f9d58';
                    outputElement.textContent = response.result || 'Command executed';
                } else {
                    outputElement.style.color = '#db4437';
                    outputElement.textContent = '错误：' + (response ? .error || 'Failed to execute command');
                }

                resultElement.appendChild(commandElement);
                resultElement.appendChild(outputElement);

                resultArea.appendChild(resultElement);
                resultArea.scrollTop = resultArea.scrollHeight;

                // 清空输入框
                commandInput.value = '';
            }
        );
        return;
    }

    try {
        // 使用 Function 构造函数来执行命令，允许返回结果
        const result = new Function('return ' + command)();

        // 显示执行结果
        const resultElement = document.createElement('div');
        resultElement.style.cssText = `
            margin-bottom: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid #444;
        `;

        // 添加命令
        const commandElement = document.createElement('div');
        commandElement.style.color = '#4285f4';
        commandElement.textContent = '> ' + command;

        // 添加结果
        const outputElement = document.createElement('div');
        outputElement.style.color = '#0f9d58';

        // 根据结果类型显示不同内容
        if (result === undefined) {
            outputElement.textContent = 'undefined';
        } else if (result === null) {
            outputElement.textContent = 'null';
        } else if (typeof result === 'object') {
            try {
                outputElement.textContent = JSON.stringify(result, null, 2);
            } catch (e) {
                outputElement.textContent = result.toString();
            }
        } else {
            outputElement.textContent = result.toString();
        }

        resultElement.appendChild(commandElement);
        resultElement.appendChild(outputElement);

        resultArea.appendChild(resultElement);
        resultArea.scrollTop = resultArea.scrollHeight;

        // 清空输入框
        commandInput.value = '';
    } catch (error) {
        // 显示错误信息
        const errorElement = document.createElement('div');
        errorElement.style.cssText = `
            margin-bottom: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid #444;
        `;

        // 添加命令
        const commandElement = document.createElement('div');
        commandElement.style.color = '#4285f4';
        commandElement.textContent = '> ' + command;

        // 添加错误信息
        const errorOutput = document.createElement('div');
        errorOutput.style.color = '#db4437';
        errorOutput.textContent = '错误：' + error.message;

        errorElement.appendChild(commandElement);
        errorElement.appendChild(errorOutput);

        resultArea.appendChild(errorElement);
        resultArea.scrollTop = resultArea.scrollHeight;
    }
}

// 清除命令结果
function clearCommandResult() {
    const resultArea = document.getElementById('ws-debugger-result');
    if (resultArea) {
        resultArea.innerHTML = '';
    }
}

// 显示或隐藏调试面板
function toggleDebugPanel() {
    if (!debugPanel) {
        initDebugPanel();
    }

    isDebugPanelVisible = !isDebugPanelVisible;
    debugPanel.style.display = isDebugPanelVisible ? 'flex' : 'none';

    if (isDebugPanelVisible) {
        updateDebugPanel();
    }
}

// 更新调试面板内容
function updateDebugPanel() {
    if (!debugPanel || !isDebugPanelVisible) {
        return;
    }

    const content = document.getElementById('ws-debugger-content');
    content.innerHTML = '';

    if (debugData.length === 0) {
        content.textContent = '暂无调试数据';
        return;
    }

    // 显示最新的 20 条数据
    const recentData = debugData.slice(-20);

    recentData.forEach((item, index) => {
        const itemElement = document.createElement('div');
        itemElement.style.cssText = `
      padding: 5px;
      border-bottom: 1px solid #444;
      margin-bottom: 5px;
    `;

        const timestamp = document.createElement('div');
        timestamp.style.color = '#999';
        timestamp.style.fontSize = '10px';
        timestamp.textContent = `[${new Date().toLocaleTimeString()}]`;

        const data = document.createElement('pre');
        data.style.margin = '3px 0';
        data.style.whiteSpace = 'pre-wrap';
        data.style.wordBreak = 'break-all';
        data.textContent = JSON.stringify(item, null, 2);

        itemElement.appendChild(timestamp);
        itemElement.appendChild(data);
        content.appendChild(itemElement);
    });

    // 滚动到底部
    content.scrollTop = content.scrollHeight;
}

// 更新状态栏
function updateStatus(message) {
    if (!debugPanel) {
        return;
    }

    const statusBar = document.getElementById('ws-debugger-status');
    if (statusBar) {
        statusBar.textContent = `状态：${message}`;
    }
}

// 添加调试数据
function addDebugData(data) {
    debugData.push(data);
    if (debugData.length > 100) {
        debugData.shift();
    }
    updateDebugPanel();
}

// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'debug_data') {
        addDebugData(message.data);
    } else if (message.type === 'connection_status') {
        if (message.status === 'connected') {
            updateStatus('已连接');
        } else if (message.status === 'disconnected') {
            updateStatus('未连接');
        } else if (message.status === 'error') {
            updateStatus(`错误：${message.error || 'Unknown error'}`);
        }
    }
});

// 创建悬浮按钮以显示/隐藏调试面板
function createFloatingButton() {
    const button = document.createElement('div');
    button.id = 'ws-debugger-button';
    button.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #4285f4;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    z-index: 9998;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    font-size: 24px;
    font-weight: bold;
    font-family: monospace;
  `;
    button.textContent = 'DB';
    button.title = 'Toggle WebSocket Debugger';

    button.addEventListener('click', toggleDebugPanel);
    document.body.appendChild(button);
}

// 初始化，在 DOM 加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createFloatingButton);
} else {
    createFloatingButton();
}

// 检查页面上是否存在调试相关参数
function checkForDebuggerParams() {
    const url = new URL(window.location.href);
    const showDebugger = url.searchParams.get('showDebugger');

    if (showDebugger === 'true') {
        setTimeout(() => {
            // 保证在页面加载后显示
            if (!isDebugPanelVisible) {
                toggleDebugPanel();
            }
        }, 1000);
    }
}

// 页面加载时检查调试参数
checkForDebuggerParams();